import { ref } from 'vue'
import { listDictData } from '@/api/system/dict'

// 字典数据缓存
const dictCache = new Map<string, any[]>()

// 获取字典数据
export async function getDictData(type: string) {
  // 如果缓存中存在，直接返回
  if (dictCache.has(type)) {
    return dictCache.get(type)
  }

  try {
    const res = await listDictData({
      pageNum: 1,
      pageSize: 100,
      dictType: type,
    })
    const list = res.data.list || []
    // 只缓存启用的字典项
    const enabledList = list.filter((item) => item.status === 1)
    dictCache.set(type, enabledList)
    return enabledList
  } catch (error) {
    console.error('获取字典数据失败:', error)
    return []
  }
}

// 获取字典选项
export function useDictOptions(type: string) {
  const options = ref<any[]>([])
  const ready = ref(false)

  // 立即加载字典数据
  getDictData(type).then((list) => {
    options.value = list.map((item) => ({
      label: item.label,
      value: item.value,
      config: item.config,
      sort: item.sort,
    }))
    ready.value = true
  })

  return {
    options,
    ready,
  }
}

// 根据字典值获取标签
export async function getDictLabel(type: string, value: string | number) {
  const list = await getDictData(type)
  const item = list.find((item) => item.value === value)
  return item ? item.label : ''
}

// 获取字典配置
export const getDictConfig = async (
  dictType: string,
  dictValue: string,
): Promise<string | undefined> => {
  const list = await getDictData(dictType)
  const option = list.find((item) => item.value === dictValue)
  return option?.config
}

// 清除字典缓存
export function clearDictCache(type?: string) {
  if (type) {
    dictCache.delete(type)
  } else {
    dictCache.clear()
  }
}
